﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;

namespace Perceptron.Engine
{
    public class ImageLoaderHelper
    {
        public static IEnumerable<ClassImage> LoadObjects()
        {
            var directoryInfo = new DirectoryInfo("..\\..\\..\\Objects");
            int classId = 0;
            foreach (var dir in directoryInfo.GetDirectories())
            {
                foreach (var file in dir.GetFiles())
                {
                    var bitmap = new Bitmap(file.FullName);
                    var bytes = bitmap.Binarize<byte>(0, 1).OfType<byte>().ToArray();
                    yield return new ClassImage(classId, dir.Name, file, new BinaryLineImage(bytes));
                }
                classId++;
            }
        }

        public static byte[] AddNoise(byte[] source, double value)
        {
            var rand = new Random();
            byte[] copy = new byte[source.Length];
            Array.Copy(source, copy, source.Length);
            int count = (int)(value * copy.Length);
            for (int i = 0; i < count; ++i)
            {
                var x = rand.Next(0, copy.Length);
                copy[x] = source[x] == 0 ? (byte) 1 : (byte) 0;
            }
            return copy;
        }

        public static Bitmap ConvertToBitmap(byte[] bytes, int width, int height)
        {
            var bitmap = new Bitmap(width, height);
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    bitmap.SetPixel(x, y, bytes[x * width + y] == 1  ? Color.GreenYellow : Color.Black);
                }
            }

            return bitmap;
        }
    }
}
